package com.lpf.www.service;

import com.lpf.www.common.dto.ResponseMsg;
import com.lpf.www.common.entity.User;
import com.lpf.www.common.utils.*;
import com.lpf.www.dao.UserDao;
import com.lpf.www.redis.UserRedis;
import com.lpf.www.utils.CommonMethod;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @Author lpf
 * @Date 2022/1/2 下午9:38
 * @ProjectName live-streaming-os
 * @Version 1.0
 * @Description:
 */
@Service
public class UserService {
    private final ResponseMsg responseMsg = new ResponseMsg();
    private final CookieTools cookieTools = new CookieTools();

    private UserDao userDao;
    private UserRedis userRedis;

    @Autowired
    public void setUserDao(UserDao userDao, UserRedis userRedis) {
        this.userDao = userDao;
        this.userRedis = userRedis;
    }

    public ResponseMsg userLogin(User user) {
        //通过用户名来查找用户，然后判断用户输入是否正确
        User selectUserByUsername = userDao.selectUserByUsername(user.getUsername());
        if (selectUserByUsername != null && user.getPassword().equals(selectUserByUsername.getPassword())) {
            responseMsg.setResCode(CommonData.SUCCESS_CODE);
            responseMsg.setResMsg("登录成功！");
            //将该用户的信息保存到redis中
            userRedis.saveUserInfoToJedis(user);
            //登录成功后设置该用户的cookie
            CommonMethod.setUserCookie(user.getUsername(), CommonData.LOGIN_USERNAME, cookieTools);
        } else {
            responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
            responseMsg.setResMsg("登录失败，帐号或用户名错误！");
        }
        return responseMsg;
    }

    /**
     * 当用户登录的时候自动获取帐号和密码
     *
     * @return
     */
    public ResponseMsg getUserInfo() {
        String username = cookieTools.getCookie(CommonData.LOGIN_USERNAME);
        User user = null;
        if (!DataHandler.isEmpty(username)) {
            //先从redis中获取数据，如果获取不到，就去数据库中获取，并且保存到redis中，最后返回数据
            User userInfoFromJedis = userRedis.getUserInfoFromJedis(username);
            if (userInfoFromJedis == null) {
                user = userDao.selectUserByUsername(username);
                userRedis.saveUserInfoToJedis(user);
            } else {
                user = userInfoFromJedis;
            }
            responseMsg.setResCode(CommonData.SUCCESS_CODE);
            responseMsg.setResMsg("请求成功！");
            responseMsg.setResObj(user);
        } else {
            responseMsg.setResCode(CommonData.NOT_REMEMBER_ME);
            responseMsg.setResMsg("没有记住密码进行登录");
            responseMsg.setResObj(username);
        }
        return responseMsg;
    }

    /**
     * 管理员注册，将管理员信息插入到数据库中，并且保存到cookie中，当返回登录界面时自动回显
     *
     * @param user
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public ResponseMsg insertUser(User user, String verificationCode) {
        User registerUser = userDao.selectUserByUsername(user.getUsername());
        if (registerUser == null) {
            registerUser = userDao.selectUserByEmail(user.getEmail());
            if (registerUser == null) {
                if (verificationCode.equals(VerificationCode.getCode(user.getPhone())) && VerificationCode.getCodeTTL(user.getPhone()) >= 300) {
                    cookieTools.save(CommonData.LOGIN_USERNAME, user.getUsername(), CommonData.REMEMBER_PASSWORD_TIME);
                    //将密码进行md5加密
                    String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
                    user.setPassword(password);
                    int res = userDao.insertUser(user);
                    if (res == 1) {
                        responseMsg.setResCode(CommonData.SUCCESS_CODE);
                        responseMsg.setResMsg("注册成功！");
                        //注册成功后将用户信息保存到redis中
                        userRedis.saveUserInfoToJedis(user);
                        VerificationCode.delCode(user.getPhone());
                    }
                } else if (!verificationCode.equals(VerificationCode.getCode(user.getPhone()))) {
                    responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                    responseMsg.setResMsg("无效的验证码!");
                } else if (VerificationCode.getCodeTTL(user.getPhone()) < 300) {
                    responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                    responseMsg.setResMsg("验证码已经失效，请重新获取！");
                }
            } else {
                responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                responseMsg.setResMsg("该邮箱已被注册，请更换邮箱！");
            }
        } else {
            responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
            responseMsg.setResMsg("该用户名已经被注册，请更换用户名！");
        }
        return responseMsg;
    }

    /**
     * 获取验证码
     *
     * @param phone
     * @return
     */
    public ResponseMsg getVerificationCode(String phone) {
        User user = userDao.selectUserByPhone(phone);
        if (user == null) {
            if (VerificationCode.saveCode(phone)) {
                String code = VerificationCode.getCode(phone);
                System.out.println("您的验证码是：" + code + "(5分钟之内有效)。");
                responseMsg.setResCode(CommonData.SUCCESS_CODE);
                responseMsg.setResMsg("验证码发送成功！");
            } else {
                responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                responseMsg.setResMsg("验证码获取失败，请稍后重新获取!");
            }
        } else {
            responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
            responseMsg.setResMsg("该手机号已被注册！");
        }
        return responseMsg;
    }

    /**
     * 获取用于登录的验证码
     *
     * @param phone
     * @return
     */
    public ResponseMsg getVerificationCodeToLogin(String phone) {
        User user = userDao.selectUserByPhone(phone);
        if (user != null) {
            if (VerificationCode.saveCode(phone)) {
                String code = VerificationCode.getCode(phone);
                System.out.println("您的验证码是：" + code + "(5分钟之内有效)。");
                responseMsg.setResCode(CommonData.SUCCESS_CODE);
                responseMsg.setResMsg("验证码发送成功！");
            } else {
                responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                responseMsg.setResMsg("验证码获取失败，请稍后重新获取!");
            }
        } else {
            responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
            responseMsg.setResMsg("该手机号未注册！");
        }
        return responseMsg;
    }

    /**
     * 验证码登录
     *
     * @param phone
     * @param verificationCode
     * @return
     */
    public ResponseMsg loginByCode(String phone, String verificationCode) {
        User user = userDao.selectUserByPhone(phone);
        if (user != null) {
            if (verificationCode.equals(VerificationCode.getCode(phone)) && VerificationCode.getCodeTTL(user.getPhone()) >= 300) {
                responseMsg.setResCode(CommonData.SUCCESS_CODE);
                responseMsg.setResMsg("登录成功！");
                VerificationCode.delCode(phone);
            } else if (!verificationCode.equals(VerificationCode.getCode(user.getPhone()))) {
                responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                responseMsg.setResMsg("无效的验证码!");
            } else if (VerificationCode.getCodeTTL(user.getPhone()) < 300) {
                responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
                responseMsg.setResMsg("验证码已经失效，请重新获取！");
            }
        } else {
            responseMsg.setResCode(CommonData.ILLEGAL_ERROR_CODE);
            responseMsg.setResMsg("该手机号未注册！");
        }
        return responseMsg;
    }
}
